import '@/assets/css/index.less';
import { getCategoryList } from '@/services/category';
import {
  batchDelete,
  getTopicInfoList,
  topicApprove,
  topicChange,
  topicDelete,
} from '@/services/topic';
import {DeleteOutlined, FileTextOutlined, SearchOutlined, UndoOutlined} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { history, useLocation } from 'umi';
import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Table,
  TreeSelect,
} from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn'
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import {useModel} from "@@/plugin-model/useModel";
import {LocalFormat} from "@/utils/localHelper";
const { RangePicker } = DatePicker;

const TableList: React.FC = (props) => {
  const location = useLocation();
  const [isShow, setIsShow] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRows, setSelectedRows] = useState<any>();
  const [shyy, setShyy] = useState<string>('');

  //部门下拉框
  const [groupOptions, setGroupOptions] = useState([]);
  //默认下拉部门
  const [groupId, setGroupId] = useState<number>(location.state?.groupId);
  //查询list
  const [dataList, setDataList] = useState([]);
  //tree
  const [treeData, setTreeData] = useState([]);

  //总数
  const [total, setTotal] = useState(40);
  //page
  const [page, setPage] = useState(1);
  //pageSize
  const [pageSize, setPageSize] = useState(10);
  //分页
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });

  //select
  const [selectedTreeData, setSelectedTreeData] = useState([]);
  const [lbxz, setLbxz] = useState([]);

  //主题options
  const themeOptions = [
    {
      value: '',
      label: '全部主题',
    },
    {
      value: '0',
      label: '一天内的主题',
    },
    {
      value: '1',
      label: '一周内的主题',
    },
    {
      value: '2',
      label: '一月内的主题',
    },
    {
      value: '3',
      label: '一年内的主题',
    },
    {
      value: '4',
      label: '两年内的主题',
    },
  ];

  //状态options
  const ztOptions = [
    { value: 'yfb', label: '已发布' },
    { value: 'shbtg', label: '审核不通过' },
    { value: 'dsh', label: '待审核' },
  ];
  //排序options
  const pxhOptions = [
    { value: '0', label: '时间升序' },
    { value: '1', label: '时间倒序' },
  ];

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleMoreRemove = async (selectedRows) => {
    if (!selectedRows) return true;
    const res = await batchDelete(selectedRows.map((row) => row.id));
    if (res.code == '0') {
      message.success('已删除！');
      queryData();
    }
    return true;
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleRemove = async (row: any) => {
    if (!row) return true;
    try {
      const res = await topicDelete({
        id: row.id,
      });
      if (res.code == '0') {
        message.success('已删除！');
        queryData();
      }

      return true;
    } catch (error) {
      message.error('删除失败！');
      return false;
    }
  };

  //更改树结构
  const changeTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
      const element = data[i];

      element.value = element.id;
      element.title = element.name;
      if (element.children && element.children.length > 0) {
        changeTreeData(element.children);
      }
    }
    return data;
  };
  //查询分类
  const getCategory = () => {
    const params = {
      type: 'topic',
      roleId: currentUser?.roleId,
    };
    //获取组list
    getCategoryList(params).then(async (res) => {
      const data = changeTreeData(res.data);
      setTreeData(data);
    });
  };

  useEffect(() => {
    getCategory();
  }, []);

  useEffect(() => {
    queryData();
  }, [page, pageSize, selectedTreeData]);

  const jumpPublish = (record: any) => {
    history.push({
      pathname: '/consultCenter/publishArticle',
      state: {
        formValues: record,
      },
    });
  };

  const columns: ProColumns<any>[] = [
    {
      title: '分类',
      align: 'center',
      dataIndex: 'classifyName',
    },

    {
      title: '标题',
      align: 'center',
      dataIndex: 'title',
    },
    {
      title: '发布者',
      align: 'center',
      width: 120,
      dataIndex: 'fbrmc',
    },
    // {
    //   title: '部门',
    //   dataIndex: 'fbbm',
    //   align: 'center',
    //   render: (_, record) => {
    //     let item = groupOptions.filter((item) => item.value == record.fbbm);
    //     if (item.length > 0) {
    //       return item[0].label;
    //     }
    //     return '';
    //   },
    // },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '状态',
      align: 'center',
      width: 120,
      dataIndex: 'zt',
    },
    {
      title: '发布时间',
      align: 'center',
      dataIndex: 'publishtime',
      valueType: 'dateTime',
    },
    {
      title: '排序',
      align: 'center',
      width: 90,
      dataIndex: 'pxh',
    },
    {
      title: '浏览量',
      align: 'center',
      width: 90,
      dataIndex: 'visitnum',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            <a key="edit" onClick={() => jumpPublish(record)}>

              <Button shape={'round'} icon={<FileTextOutlined />}>
                详情
              </Button>
            </a>

            <a key="delete" onClick={() => handleRemove(record)} style={{ color: 'red' }}>
              <Button danger shape={'round'} icon={<DeleteOutlined />}>
                删除
              </Button>
            </a>
          </Space>
        );
      },
    },
  ];

  const [form] = Form.useForm();
  //初始化搜索区域
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          initialValues={{
            creater: '0',
            px: '1',
          }}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
          onValuesChange={() => queryData(true)}
        >
          <Row style={{ width: '100%' }}>
            <Col span={3}>
              <Form.Item name="searchKey">
                <Input placeholder="关键字" />
              </Form.Item>
            </Col>

            <Col span={3}>
              <Form.Item name="classify">
                <TreeSelect treeData={treeData} placeholder="选择分类" allowClear />
              </Form.Item>
            </Col>

            <Col span={3}>
              <Form.Item name="titleType">
                <Select placeholder="请选择" options={themeOptions} allowClear />
              </Form.Item>
            </Col>

            <Col span={5}>
              <Form.Item label="发布时间" name="dataDate">
                <RangePicker locale={locale} allowEmpty={[true, true]} />
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item name="zt">
                <Select placeholder="请选择" allowClear options={ztOptions} />
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item name="creater">
                <Select
                  placeholder="请选择"
                  options={[
                    { value: '0', label: '全部主题' },
                    { value: '1', label: '仅我发表的' },
                  ]}
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item name="px">
                <Select placeholder="请选择" options={pxhOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={2} className="basic-search-form-submit-btn" style={{ display: 'flex' }}>
              <Button
                onClick={() => {
                  setGroupId(null);
                  form.resetFields();
                  queryData(true);
                }}
              >
                <UndoOutlined />
                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData(true)}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  //查询
  const queryData = async (pageChanged) => {
    setIsLoading(true);
    let values = form.getFieldsValue();
    //分类
    if (selectedTreeData.length > 0) {
      values.classify = selectedTreeData;
    }

    if (values.dataDate != null && values.dataDate != undefined) {
      values.timeStart = !!values.dataDate[0]
        ? moment(values.dataDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
        : null;
      values.timeEnd = !!values.dataDate[1]
        ? moment(values.dataDate[1]).format('YYYY-MM-DD') + ' 23:59:59'
        : null;
    }
    let params = {};
    if (pageChanged) {
      //搜索状态，page为1
      params = {
        page: 1,
        pageSize: pageSize,
      };
      setPage(1);
    } else {
      //搜索状态
      params = {
        page: page,
        pageSize: pageSize,
      };
    }
    const msg = await getTopicInfoList({...params,...values,roleId: currentUser?.roleId,
    });
    setIsLoading(false);
    setDataList(msg.data.list);
    if (pageChanged) setPagination({ ...pagination, total: msg.data.total, current: 1 });
    else setPagination({ ...pagination, total: msg.data.total });
  };

  const handleTableChange = (pagination: any) => {
    setPagination({ ...pagination });
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  const [isOrder, setIsOrder] = useState(false);

  //order
  const [orderNum, setOrderNum] = useState(0);

  const [isSh, setIsSh] = useState(false);

  //是否是专题
  const [isZt, setIsZt] = useState(false);
  //order
  const [shNum, setShNum] = useState(0);
  //排序弹框
  const handleOrderOk = async () => {
    const params = {
      id: currentRow.id,
      pxh: orderNum,
    };
    const res = await topicChange(params);
    if (res.code == '0') {
      message.success('修改成功！');
      queryData();
    }
    setIsOrder(false);
  };

  const handleOrderCancel = () => {
    setIsOrder(false);
  };

  const onOrderChange = (e: any) => {
    setOrderNum(e.target.value);
  };

  //类别弹框
  const handleLbxzOk = async () => {
    const params = {
      id: currentRow.id,
      classify: lbxz,
    };
    const res = await topicChange(params);
    if (res.code == '0') {
      message.success('修改成功！');
      queryData();
    }
    setIsShow(false);
  };
  //审核弹框
  const handleShOk = async () => {
    let params = {
      id: currentRow.id,
      sftg: shNum,
    };
    if (shNum == 0) {
      params.sbyy = shyy;
    }
    const res = await topicApprove(params);
    if (res.code == '0') {
      queryData();
    }
    setIsSh(false);
  };

  const handleShCancel = () => {
    setIsSh(false);
  };

  const onShChange = (e: any) => {
    setShNum(e.target.value);
  };
  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      {_initSearchForm()}
      <div className="centerBody">
        <Row>
          <Col span={2} offset={22} className="firstRow">
            <Button
              type="primary"
              danger
              key="danger"
              onClick={() => {
                handleMoreRemove(selectedRows);
              }}
            >
              <DeleteOutlined />
              批量删除
            </Button>
          </Col>

          <Col span={24}>
            <Table
              loading={isLoading}
              scroll={{ x: 1350 }}
              size="small"
              actionRef={actionRef}
              rowKey="id"
              search={false}
              tableStyle={{ textAlign: 'center' }}
              options={false}
              onChange={handleTableChange}
              dataSource={dataList}
              columns={columns}
              pagination={pagination}
              rowSelection={{
                onChange: (_, selectedRows) => {
                  setSelectedRows(selectedRows);
                },
              }}
            />
          </Col>
        </Row>
      </div>
    </PageContainer>
  );
};

export default TableList;
